package com.electric.qrapp.utils.function

import android.content.Context
import android.graphics.drawable.Drawable
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.*
import androidx.core.app.ActivityCompat
import com.electric.qrapp.R
import dagger.hilt.android.internal.managers.ViewComponentManager

/**
 * 获取View
 * @param id
 * @param viewGroup
 * @return
 */

fun layoutInflater(context: Context, @LayoutRes id: Int, viewGroup: ViewGroup? = null): View {
    return LayoutInflater.from(context).inflate(id, viewGroup)
}

/**
 *设置颜色 前后都包括
 * @param color
 * @param start
 * @param end
 * @return
 */

fun conversionColor(content: String, @ColorInt color: Int, start: Int, end: Int): SpannableString {
    val ss = SpannableString(content)
    ss.setSpan(ForegroundColorSpan(color), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
    return ss
}


fun findColors(context: Context, @ColorRes color: Int): Int =
    ActivityCompat.getColor(context, color)

fun findDrawable(context: Context, @DrawableRes drawableId: Int): Drawable? =
    ActivityCompat.getDrawable(context, drawableId)


//添加了状态栏高度的视图 一般用做 状态栏透明 标题栏覆盖状态栏 但它又不是图片的情况 如 HomeFragment 实现滑动效果
//对于 view_app_title 这类 height 高度不确定的来讲 必须指定其高度 否则不起作用  @dimen/app_title_with_search
fun addStatusBarHeightPadding(view: ViewGroup) {
    val layoutParams = view.layoutParams
    var height = layoutParams.height
    val statusBarHeight = getStatusBarHeight(view.context)
    layoutParams.height = height + statusBarHeight
    view.setPadding(
        view.paddingLeft,
        statusBarHeight + view.paddingTop,
        view.paddingRight,
        view.paddingBottom
    )
    view.layoutParams = layoutParams
}


fun getContexts(context: Context): Context {
    return if (context is ViewComponentManager.FragmentContextWrapper) {
        context.baseContext
    } else context
}

/**
 * return statusBar's Height in pixels
 */
fun getStatusBarHeight(context: Context): Int {
    var result = 0
    val resId = context.resources.getIdentifier("status_bar_height", "dimen", "android")
    if (resId > 0) {
        result = context.resources.getDimensionPixelOffset(resId)
    } else {
        result = dip2px(context, context.resources.getDimension(R.dimen.status_bar_height))
    }
    return result
}

fun dip2px(context: Context, dpValue: Float): Int {
    val scale = context.resources.displayMetrics.density
    return (dpValue * scale + 0.5f).toInt()
}

fun px2dip(context: Context, pxValue: Float): Int {
    val scale = context.resources.displayMetrics.density
    return (pxValue / scale + 0.5f).toInt()
}

fun dimenToPx(context: Context, @DimenRes id: Int):Int {
   return context.resources.getDimension(id).toInt()
}